import { saveArticle, fetchLatestApi, fetchArticleByIdApi } from '../services/articles';
import { message } from 'antd';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'articles',
  state: {
    // isSavedSuccess: false
    latest: [],
    entities: {},
    currentArticle: {},
  },
  effects: {
    *addArticle({ payload }, { call, put }) {
      yield call(saveArticle, payload);
      message.success('保存成功！');
      yield put(routerRedux.push('/articles/latest'));
    },
    *fetchLatest(_, { call, put }) {
      const resp = yield call(fetchLatestApi);
      yield put({
        type: 'setLatest',
        payload: resp,
      });
    },
    *fetchArticleById({ payload }, { call, put }) {
      // doSomething
      const resp = yield call(fetchArticleByIdApi, payload);
      yield put({
        type: 'setCurrentArticle',
        payload: resp,
      });
    },
    *deleteArticle({articleId, latestArticle}, {call, put}){
            
    }
  },
  reducers: {
    // setSuccessFlag(state) {
    //     return {...state, isSavedSuccess: true}
    // }
    setLatest(state, action) {
      const newEntities = action.payload.reduce((acc, art) => {
        acc[art.id] = art;
        return acc;
      }, {});
      return {
        ...state,
        latest: action.payload,
        entities: {
          ...state,
          ...newEntities,
        },
      };
    },
    setCurrentArticle(state, action) {
      return {
        ...state,
        // currentArticle:action.payload
        entities: {
          ...state.entities,
          [action.payload.id]: action.payload,
        },
      };
    },
  },
};
